//
//  BKGDWebViewController.m
//  bestkeep
//
//  Created by 毛韶谦 on 2016/11/10.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKGDWebViewController.h"
#import "BKGDCommon.h"

@interface BKGDWebViewController ()<UIWebViewDelegate, UIScrollViewDelegate>

@property(nonatomic,strong) UIWebView *webView;

@property(nonatomic,assign) BOOL isLoading;
@property(nonatomic,assign) BOOL isCompleted;

@property(nonatomic,strong) UIImageView *backToTop;

@end

@implementation BKGDWebViewController

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if(_baseURLString && !_isLoading && !_isCompleted) {
        
        self.isLoading = YES;
        
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:_baseURLString]];
        [request setValue:@"iphone" forHTTPHeaderField:@"User-Agent"];
        
        NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
        NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
        __weak typeof(self) weakSelf = self;
        NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if(!weakSelf) {
                return;
            }
            
            weakSelf.isLoading = NO;
            
            if(error) {
                return;
            }
            if(!data) {
                return;
            }
            __strong typeof(weakSelf) strongSelf = weakSelf;
            
            NSString *htmlString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            [strongSelf.webView loadHTMLString:htmlString baseURL:nil];
            
            weakSelf.isCompleted = YES;
        }];
        
        [dataTask resume];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initializeComponent];
}

-(void)initializeComponent {
    
    _webView = [[UIWebView alloc] init];
    _webView.delegate = self;
    _webView.scrollView.delegate = self;
    _webView.backgroundColor = self.view.backgroundColor;
    [self.view addSubview:_webView];
    
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
    header.lastUpdatedTimeLabel.hidden = YES;
    [header setTitle:BKGDLocalizedString(@"BKGDWebRefreshHeaderIdle") forState:MJRefreshStateIdle];
    [header setTitle:BKGDLocalizedString(@"BKGDWebRefreshHeaderWillRefresh") forState:MJRefreshStateWillRefresh];
    [header setTitle:BKGDLocalizedString(@"BKGDWebRefreshHeaderPulling") forState:MJRefreshStatePulling];
    [header setTitle:BKGDLocalizedString(@"BKGDWebRefreshHeaderRefreshing") forState:MJRefreshStateRefreshing];
    header.stateLabel.font = [UIFont systemFontOfSize:14];
    header.stateLabel.textColor = [UIColor lightGrayColor];
    header.hidden = YES;
    header.arrowView.image = [UIImage imageNamed:@"BKGDPullDown"];
    _webView.scrollView.mj_header = header;
    
    _backToTop = [[UIImageView alloc] init];
    _backToTop.image = [UIImage imageNamed:@"BKGDWebTop"];
    _backToTop.userInteractionEnabled = YES;
    _backToTop.hidden = YES;
    UITapGestureRecognizer *backTop = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backTop)];
    [_backToTop addGestureRecognizer:backTop];
    [self.view addSubview:_backToTop];
    [self.view bringSubviewToFront:_backToTop];
    
    [self makeConstraints];

    [self webViewContentConfig];
}

-(void)makeConstraints {
    [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsZero);
    }];
    
    [_backToTop mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(self.view.mas_right).offset(-12);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(-64);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(30);
    }];
}

//-(void)setBaseURLString:(NSString *)baseURLString {
//    if(_baseURLString && [_baseURLString isEqualToString:baseURLString]) {
//        return;
//    } else {
//        _baseURLString = baseURLString;
//        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:_baseURLString]];
//        [_webView loadRequest:request];
//    }
//}

-(void)webViewContentConfig {
    if(!UIEdgeInsetsEqualToEdgeInsets(UIEdgeInsetsZero, _contentInset)) {
        
        _webView.scrollView.contentInset = _contentInset;
        _webView.scrollView.scrollIndicatorInsets = _contentInset;
        
        _webView.scrollView.contentOffset = CGPointMake(0, -_contentInset.top);
    }
}

#pragma -mark header refresh
-(void)headerRefresh {
    
    [_webView.scrollView.mj_header endRefreshing];
    if(_headerRefreshCallback) {
        _headerRefreshCallback();
    }
    
}

-(void)allowHeaderRefresh:(BOOL)flag {
    _webView.scrollView.mj_header.hidden = !flag;
}

#pragma -mark webView tableView

-(void)webViewDidStartLoad:(UIWebView *)webView {
    
}

-(void)webViewDidFinishLoad:(UIWebView *)webView {
    self.title = [_webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
    [_webView stringByEvaluatingJavaScriptFromString:[self javaScript]];
    
    [self webViewContentConfig];
}

-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
    NSLog(@"BKGDWebViewController:%@",error);
}

/**
 *  JavaScript
 */
-(NSString*)javaScript {
    NSString *javaScript = @"document.documentElement.style.webkitUserSelect='none';\
    document.documentElement.style.webkitTouchCallout='none';\
    ";
    return javaScript;
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView {
    _backToTop.hidden = (scrollView.contentOffset.y > 100) ? NO : YES;
}

//返回顶部
-(void)backTop{
    _backToTop.hidden = YES;
    [_webView.scrollView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}

@end
